package com.molyfun.core.support.qiniu;


import java.util.ResourceBundle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.PropertySource;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛 云存储工具类 
 * shidongsheng
 * 2016.7.11
 */

@PropertySource(value = { "classpath:config/qiniu.properties" })
public class FileQiniuManager{
	private static Logger logger = LogManager.getLogger();
	private static Auth auth;
	private static UploadManager uploadManager;
	public static final ResourceBundle QINIU = ResourceBundle.getBundle("config/qiniu");

	static { 
		try {
			//密钥配置
			auth = Auth.create(QINIU.getString("access_key"), QINIU.getString("secret_key"));
			//创建上传对象
			uploadManager = new UploadManager();
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	//简单上传，使用默认策略，只需要设置上传的空间名就可以了
	public static String getUpToken(){
		return auth.uploadToken(QINIU.getString("bucketname"));
	}

	public static void upload(byte[] data,String key) throws Exception{
		try {
			//调用put方法上传
//			Response res = uploadManager.put(filePath, key, getUpToken());
			Response res = uploadManager.put(data, key, getUpToken());
			//打印返回的信息
			System.out.println(res.bodyString()); 
		} catch (QiniuException e) {
			Response r = e.response;
			logger.error(r.toString());
			throw new Exception("qiniu error");
		}       
	}

}
